#!/usr/bin/python

import sys,os,re
import string
import argparse
from pyh import *

FILES = []
TLIST = []

# recursive to find the log file
def get_logfile(path, pattern):
    if not os.path.isdir(path):
        filename = os.path.basename(path)
        if filename.find(string.strip(pattern)) != -1:
            abs_path = os.path.abspath(path)
            return FILES.append(abs_path)
    else:
        fls = os.listdir(path)
        for file in fls:
            get_logfile(path + "/" + file, pattern)

def get_errors(file, wfp, str_pattern, oflag):
    if not os.path.isfile(file):
        return ""

    rfp = open(file, "r")
    title = ""
    content = []
    try:
        # check the lost type line
        flag = 0  
        # check the line is fsck lost
        lflag = 0
        for line in rfp:
            # Whether line is title
            if flag == 0:
                # Whether we want to dump out .html format
                if oflag == 0:
                    if lflag == 1:
                        wfp << pre(title)
                        for ol in content:
                            wfp << pre(ol)
                else:
                    if lflag == 1:
                        wfp.write("\n")
                        wfp.write(title)
                        wfp.writelines(content)
                        # A new round of check
                title = ""
                content = []
                lflag = 0

                str = line.find(str_pattern)
                if str != -1:
                    flag = 1
                    if oflag == 1:
                        title = line
                        # wfp.write("\n")
                        # wfp.write(line)
                    else:
                        wfp << pre(line)
                    #print line,
            else:
                str1 = line.find("at")
                str2 = line.find("by ")
                if str1 != -1 or str2 != -1:
                    #print line,
                    if oflag == 1:
                        content.append(line)
                        if lflag == 0 and len(TLIST) != 0:
                            for item in TLIST:
                                pos = line.find(item)
                                if pos != -1:
                                    print pos
                                    lflag = 1
                                    break
                        else:
                            lflag = 1

                        #wfp.write(line)
                    else:
                        wfp << pre(line)
                else:
                    flag = 0
    finally:
        rfp.close()

def dump_to_html(files, name, str):
    strname = name + ".html"

    page = PyH("FSCK Memory Check Report")
    page.addCSS("//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css")
    page.addJS("//cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js")

    page << h1('FSCK Valgrind Memory Check Report', cl = 'text-center')
    
    div1 = page << div(cl = 'panel-group', id='accordion')
    for file in FILES:
        div_head = div1 << div(cl = 'panel panel-default') 
        div_head << div(cl = 'panel-heading', id='headingOne') << h4(cl = 'panel-title') \
                << a(file, href='#collapseOne')
        div2 = div_head << div(cl = 'panel-body')
        get_errors(file, div2, str, 0)
    page.printOut(strname)


def check_item(dir):
    global FILES
    global TLIST
    get_logfile(dir, "cxx")
    for fl in FILES:
        fl = os.path.basename(fl)
        TLIST.append(fl)
    FILES = []
    return TLIST

def main(argv):
    parser = argparse.ArgumentParser(description="This utility allows collect the valgrind memcheck data.\n ./collect.py -p /home/c4dev/public_html/valgrind_pfs/ilc/ilc-2016-05-26 -m val -o ilc_1.log -s 'definitely lost'")
    parser.add_argument("-p", "--path", dest="path", nargs='*', help="Specify valgrind memcheck ouput log file path.")
    parser.add_argument("-m", "--match", dest="match", nargs=1, default=" ", help="Specify the file name pattern.")
    parser.add_argument("-o", "--output", dest="output", nargs=1, default="out.log ", help="Dump the output log file.")
    parser.add_argument("-s", "--string", dest="str", nargs=1, default="definitely lost", help="Specify the search pattern string.")
    parser.add_argument("-html", dest="html", nargs='?', help="Specify the search pattern string.")
    parser.add_argument("-t", "--template", dest="template", nargs=1, default="/c4_working/work_ilc/sade/src/dart/Dart/server/src/ods/newfsck64", help="Specify the template file name direcotry.")
    args = parser.parse_args(argv)
    
    files = []

    # Add check template
    check_item("/c4_working/work_ilc/sade/src/dart/Dart/server/src/ods/newfsck64")
    #print TLIST

    wfp = open(args.output[0],'w') 
    for path in args.path:
        if os.path.isdir(path):
            print "Processing : ",path
            get_logfile(path, args.match[0])

    for file in FILES:
        #print file,
        wfp.write(file)
        wfp.write("\n")
        get_errors(file, wfp, args.str[0], 1)
        #print "\n"
        wfp.write("\n")
    wfp.close() 

    if args.html and args.html == "yes":
        dump_to_html(FILES, args.output[0], args.str[0])

if __name__ == '__main__':
    main(sys.argv[1:])
